package saiboten;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.jibble.pircbot.*;

import saiboten.actions.GetTemperatureAction;
import saiboten.actions.GetWeatherAction;
import saiboten.actions.GjettPlugin;
import saiboten.actions.LastLinksAction;
import saiboten.actions.ReplaceAction;
import saiboten.actions.SC2Action;
import saiboten.actions.SaibotenAction;
import saiboten.actions.VMAction;
import twitter.Latterboksen;

public class Saiboten extends PircBot {
	
	Random random = new Random();
	List<ChannelAction> channelActions;
	List<SenderAction> senderActions;
	Properties properties;
	List<String> channels;
	
	public void setChannelList(List<String> channels) {
		this.channels = channels;
	}

	public Saiboten() {
		setupProperties();
//		setName(properties.getProperty("bot.name"));
		setName("saiboten");
		channelActions = new ArrayList<ChannelAction>();
		channelActions.add(new GetTemperatureAction());
		channelActions.add(new GetWeatherAction());
		channelActions.add(new VMAction());
		channelActions.add(new SC2Action());
		channelActions.add(new GjettPlugin());
		channelActions.add(new SaibotenAction());
		channelActions.add(new Latterboksen());
		channelActions.add(new ReplaceAction());
		
		senderActions = new ArrayList<SenderAction>();
		senderActions.add(new LastLinksAction());
	}

	private void setupProperties() {
		try {
			properties = new Properties();
			properties.load(new FileInputStream("bot.properties"));
		}
		catch(IOException u) {
			System.out.println("Failed to load properties");
			u.printStackTrace();
			throw new RuntimeException();
		}

		
	}

	public void onMessage(String channel, String sender, String login,
			String hostname, String message) {
		handleActions(channel, sender, message);
	}

	private void handleActions(String channel, String sender, String message) {
		for(ChannelAction action : channelActions) {
			List<String> results = action.action(new ArrayList<String>(),channel, sender, message);
			for(String result : results) {
				sendMessage(channel, result);
			}
		}
		for(SenderAction action : senderActions) {
			action.action(this, sender, message);
		}
	}

	public void onDisconnect() {
		while (!isConnected()) {
			try {
				reconnect();
			} catch (Exception e) {
				try {
					Thread.sleep(10 * 60 * 1000);
				} catch (InterruptedException ie) {
					// do nothing
				}
			}
		}
	}

	public void onConnect() {
		for(String channel : channels) {
			this.joinChannel("#" + channel);
		}
	}
}
